package ar.com.sgsvm.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import ar.com.sgsvm.R;
import ar.com.sgsvm.entity.Usuario;
import ar.com.sgsvm.exceptions.IncorrectLoginException;
import ar.com.sgsvm.exceptions.NonexistentEntityException;
import ar.com.sgsvm.logic.UsuarioLogica;
import ar.com.sgsvm.view.controlPanel.AdminControlPanel;
import ar.com.sgsvm.view.controlPanel.VendedorControlPanel;

public class Login extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		EditText passwordEditText = (EditText) findViewById(R.id.password);
		passwordEditText.setOnEditorActionListener(new PasswordDoneOnEditorActionListener());
	}

	private void doLogin(View view) {
		EditText mUsername = (EditText) findViewById(R.id.username);
		EditText mPassword = (EditText) findViewById(R.id.password);
		String username = mUsername.getText().toString();
		String password = mPassword.getText().toString();
		UsuarioLogica usuarioLogica = new UsuarioLogica();
		try {
			Usuario usuario = usuarioLogica.login(username, password);
			String tipoUsuario = usuario.getTipoUsuario().getNombre();
			if (tipoUsuario.equals("admin")) {
				Intent intent = new Intent(this, AdminControlPanel.class);
				startActivity(intent);
			} else if (tipoUsuario.equals("vendedor")) {
				Intent intent = new Intent(this, VendedorControlPanel.class);
				startActivity(intent);
			}
		} catch (NonexistentEntityException n) {
			Toast.makeText(getApplicationContext(), n.getMessage(), Toast.LENGTH_SHORT).show();
		} catch (IncorrectLoginException i) {
			Toast.makeText(getApplicationContext(), i.getMessage(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class PasswordDoneOnEditorActionListener implements OnEditorActionListener {

		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_DONE) {
				InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				doLogin(v);
				return true;
			}
			return false;
		}

	}

}
